package com.rahwi.rahwi_server.Service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rahwi.rahwi_server.Entity.User;
import com.rahwi.rahwi_server.Service.Interface.ILoginService;
import com.rahwi.rahwi_server.Service.validator.Login;
import com.rahwi.rahwi_server.Service.validator.Register;
import com.rahwi.rahwi_server.Utils.token.JWTutil;
import com.rahwi.rahwi_server.vo.data.LoginData;
import com.rahwi.rahwi_server.vo.params.LoginParams;
import com.rahwi.rahwi_server.vo.params.RegisterParams;
import com.rahwi.rahwi_server.vo.results.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginService
 * @Description
 * @Date 2021/12/12 14:29
 * @Autor mjw
 * @Version 2.0
 * @ChangeIn 2021/12/17 19:04
 * @Autor dn
 */
@Service
public class LoginService implements ILoginService {

    @Autowired
    private UserService userService;

    @Autowired
    private JWTutil jwTutil;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 检查登录字段，同时生成token
     * @param loginParams
     * @UpdateTime 2021/12/17
     * @Author dn
     * @return
     */
    @Override
    @Login(notNull = {"email","password"})
    public ActionResult checkLogin(LoginParams loginParams) {
        //int id = loginParams.getUid();
        String email = loginParams.getEmail();
        String pwd = loginParams.getPassword();
        //User res = userService.getUserById(id);
        User res = userService.getUserByEmail(email).orElse(null);
        if(res == null)
            return ActionResult.fail(701,"user not found");
        else if (!pwd.equals(res.getPassword())){
            return ActionResult.fail(702, "password is not correct");
        }

        String token = jwTutil.generateToken(res.getUserId());
        LoginData data = new LoginData(token,res.getUserId(),res.getEmail(),res.getLevel(),res.getPicture());
        //redis储存token
        //登录成功，使用JWT生成token，返回token和redis中
        ObjectMapper mapper = new ObjectMapper();
        try {
            redisTemplate.opsForValue().set("TOKEN_"+token,mapper.writeValueAsString(res) ,1, TimeUnit.DAYS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return  ActionResult.success(data);
    }

    /**
     * 注册
     * @param registerParams
     * @UpdateTime 2021/12/18
     * @Author dn
     * @return
     */
    @Override
    @Register(notNull = {"username","password","email"})
    public ActionResult register(RegisterParams registerParams) {

        String email = registerParams.getEmail();
        Optional<User> res = userService.getUserByEmail(email);
        if(!res.isEmpty()) {
            System.out.println("res:" + res.toString());
            return ActionResult.fail(701, "user has existed");
        }
        User user = new User();
        //user.setUserId(userService.findAll()+1);
        user.setUserName(registerParams.getUsername());
        user.setEmail(registerParams.getEmail());
        user.setPassword(registerParams.getPassword());
        user.setLevel(0);
        userService.saveUser(user);
        return  ActionResult.success(null);
    }


}
